/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.persistence.hibernate.core;

import com.blandware.atleap.common.util.PartialCollection;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.model.core.*;
import com.blandware.atleap.persistence.core.SequenceItemDAO;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>Hibernate implementation of SequenceItemDAO.</p>
 * <p><a href="SequenceItemDAOHibernate.java.html"><i>View Source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version : $Revision: 1.5 $ : 2007/12/17 13:38:25 $
 */
public class SequenceItemDAOHibernate extends BaseDAOHibernate implements SequenceItemDAO {

	/**
	 * Creates new instance of SequenceItemDAOHibernate.
	 */
	public SequenceItemDAOHibernate() {
	}

	// ~ CRUD Methods ================================================================

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceItemDAO#createSequenceItem(com.blandware.atleap.model.core.SequenceItem, com.blandware.atleap.model.core.Sequence, com.blandware.atleap.model.core.Page) 
	 */
	public Long createSequenceItem(SequenceItem sequenceItem, Sequence sequence,
                                   Page page) {
        sequenceItem.setPosition(getFirstFreePosition(sequence.getId()));
        sequence.addSequenceItem(sequenceItem);
		sequenceItem.setPage(page);
		return (Long) getHibernateTemplate().save(sequenceItem);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceItemDAO#createSequenceItem(com.blandware.atleap.model.core.SequenceItem, com.blandware.atleap.model.core.Sequence, com.blandware.atleap.model.core.ContentResource)  
	 */
	public Long createSequenceItem(SequenceItem sequenceItem, Sequence sequence,
                                   ContentResource contentResource) {
        sequenceItem.setPosition(getFirstFreePosition(sequence.getId()));
        sequence.addSequenceItem(sequenceItem);
		sequenceItem.setContentResource(contentResource);
		return (Long) getHibernateTemplate().save(sequenceItem);
	}

    /**
	 * @see com.blandware.atleap.persistence.core.SequenceItemDAO#retrieveSequenceItem(Long) 
	 */
	public SequenceItem retrieveSequenceItem(Long sequenceItemId) {
		return (SequenceItem) getHibernateTemplate().get(SequenceItem.class, sequenceItemId);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceItemDAO#updateSequenceItem(com.blandware.atleap.model.core.SequenceItem, com.blandware.atleap.model.core.Sequence, com.blandware.atleap.model.core.Page) 
	 */
	public void updateSequenceItem(SequenceItem sequenceItem, Sequence sequence,
                                   Page page) {
		SequenceItem oldSequenceItem = sequence.updateSequenceItem(sequenceItem);
        removeFromCache(oldSequenceItem);
		sequenceItem.setPage(page);
        sequenceItem.setContentResource(null);
        getHibernateTemplate().update(sequenceItem);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceItemDAO#updateSequenceItem(com.blandware.atleap.model.core.SequenceItem, com.blandware.atleap.model.core.Sequence, com.blandware.atleap.model.core.ContentResource)  
	 */
	public void updateSequenceItem(SequenceItem sequenceItem, Sequence sequence,
                                   ContentResource contentResource) {
		SequenceItem oldSequenceItem = sequence.updateSequenceItem(sequenceItem);
        removeFromCache(oldSequenceItem);
		sequenceItem.setPage(null);
        sequenceItem.setContentResource(contentResource);
        getHibernateTemplate().update(sequenceItem);
	}

    /**
	 * @see com.blandware.atleap.persistence.core.SequenceItemDAO#deleteSequenceItem(com.blandware.atleap.model.core.SequenceItem) 
	 */
	public void deleteSequenceItem(SequenceItem sequenceItem) {
		getHibernateTemplate().delete(sequenceItem);
		sequenceItem.getSequence().removeSequenceItem(sequenceItem);
	}

	// ~ Additional methods ================================================================

	/**
	 * @see com.blandware.atleap.persistence.core.SequenceItemDAO#listSequenceItems(com.blandware.atleap.common.util.QueryInfo) 
	 */
	public PartialCollection listSequenceItems(QueryInfo queryInfo) {
		String whereClause = "";
		String orderByClause = "";
		if ( queryInfo != null ) {
			whereClause = queryInfo.getWhereClause();
			orderByClause = queryInfo.getOrderByClause();
			if ( whereClause != null && whereClause.length() != 0 ) {
				whereClause = " and " + whereClause;
			} else {
				whereClause = "";
			}
			if ( orderByClause != null && orderByClause.length() != 0 ) {
				orderByClause = " order by " + orderByClause;
			} else {
				orderByClause = " order by i.position ";
			}
		}

        boolean useCacheRegion = false;
        if (queryInfo != null && queryInfo.getQueryParameters() != null) {
            useCacheRegion = Boolean.TRUE.equals(queryInfo.getQueryParameters().get("useCacheRegion"));
        }
        String cacheRegion = null;
        if (useCacheRegion) {
            cacheRegion = "query.listSequenceItems";
        }

        Long sequenceId = null;
        if (queryInfo != null) {
            if (queryInfo.getQueryParameters() != null) {
                sequenceId = (Long) queryInfo.getQueryParameters().get("sequenceId");
            }
        }
        List list;
		Integer total = null;
		String hqlPart;
        Object[] args;
        if (sequenceId != null) {
            hqlPart = "from SequenceItem i where (i.sequence.id = ?) " + whereClause;
            args = new Object[]{sequenceId};
        } else {
            hqlPart = "from SequenceItem i " + ("".equals(whereClause) ? "" : "where " + whereClause);
            args = new Object[0];
        }

        if ( queryInfo != null && (queryInfo.getLimit() != null || queryInfo.getOffset() != null) ) {
			String hqlForTotal = "select count(i.id) " + hqlPart;
			total = findUniqueIntegerResult(hqlForTotal, args);
			if ( total == null ) {
				total = new Integer(0);
			}
		}
        // If we don't have any info about the total number of results yet or
        // we know that there's something that will be found, then fetch data
		if ( total == null || total.intValue() > 0 ) {
			String hql = "select i " + hqlPart + orderByClause;
			list = executeFind(hql, queryInfo, args, useCacheRegion, cacheRegion);
			if ( total == null ) {
				total = new Integer(list.size());
			}
		} else {
			list = new ArrayList();
		}
		return new PartialCollection(list, total);
	}

    /**
     * @see com.blandware.atleap.persistence.core.SequenceItemDAO#moveSequenceItem(com.blandware.atleap.model.core.SequenceItem, boolean)  
     */
    public void moveSequenceItem(SequenceItem sequenceItem, boolean up) {
        SequenceItem neighbourSequenceItem;
        String hql;
        String ownerHql;
        List args;

        Long ownerId = sequenceItem.getSequence().getId();
        ownerHql = "and i.sequence.id = ?";
        if (up) {
            hql = "select max(i.position) from SequenceItem i where i.position < ? ";
        } else {
            hql = "select min(i.position) from SequenceItem i where i.position > ? ";
        }
        String neighbourPositionHql = hql + ownerHql;
        args = new ArrayList();
        args.add(sequenceItem.getPosition());
        args.add(ownerId);

        Integer neighbourPosition = findUniqueIntegerResult(neighbourPositionHql, args.toArray());
        if (neighbourPosition != null) {
            String neighbourHql = "select i from SequenceItem i where i.position = ? " + ownerHql;
            args = new ArrayList();
            args.add(neighbourPosition);
            args.add(ownerId);
            neighbourSequenceItem = (SequenceItem) findUniqueResult(neighbourHql, args.toArray());
            if (neighbourSequenceItem != null) {
                Integer tempPosition = sequenceItem.getPosition();
                sequenceItem.setPosition(neighbourSequenceItem.getPosition());
                neighbourSequenceItem.setPosition(tempPosition);

                getHibernateTemplate().update(sequenceItem);
                getHibernateTemplate().update(neighbourSequenceItem);
            }
        }
    }

    /**
     * @see com.blandware.atleap.persistence.core.SequenceItemDAO#getFirstLastOccupiedPositions(Long)
     */
    public Integer[] getFirstLastOccupiedPositions(Long sequenceId) {
        ArrayList args = new ArrayList();
        String hql = "select min(i.position), max(i.position) from SequenceItem i where ";
        hql += "i.sequence.id = ?";
        args.add(sequenceId);
        Object[] objs = (Object[]) findUniqueResult(hql, args.toArray());
        Integer[] result = new Integer[2];
        result[0] = (Integer) objs[0];
        result[1] = (Integer) objs[1];
        return result;
    }

    // ~ Finders ================================================================

    // ~ Protected methods

    /**
     * Returns the least position available among items within sequence with
     * given ID.
     *
     * @param sequenceId ID of sequence which children will be considered
     * @return the least free position
     */
    protected Integer getFirstFreePosition(Long sequenceId) {
        Integer result = getFirstLastOccupiedPositions(sequenceId)[1];
        if (result == null) {
            result = new Integer(0);
        } else {
            result = new Integer(result.intValue() + 1);
        }
        return result;
    }

}